// 获取表单字段
function getFormFields() {
  const fields = [];
  const inputs = document.querySelectorAll('input[type="text"], input[type="email"], input[type="tel"], textarea');
  inputs.forEach(input => {
    fields.push({
      name: input.name || input.id,
      type: input.type,
      selector: generateSelector(input),
      id: input.id
    });
  });
  return fields;
}

// 填充表单字段
function fillFormFields(values) {
  for (const fieldId in values) {
    if (!values[fieldId]) continue;
    
    try {
      if (fieldId === 'field8440') { // 项目名称
        const currentTime = Date.now();
        const randomTime = Date.now() + 1000;
        const apiUrl = `https://oa.shenglong-info.com/api/public/browser/complete/161?q=${values[fieldId]}&type=browser.xmmc_all&fielddbtype=browser.xmmc_all&currenttime=${currentTime}&requestid=-1&workflowid=103&htgs_${currentTime}=0&wfid=103&billid=-93&isbill=1&f_weaver_belongto_userid=278&f_weaver_belongto_usertype=0&wfTestStr=&fieldid=8440&viewtype=0&fromModule=workflow&wfCreater=278&__random__=${randomTime}`;
        
        fetch(apiUrl, {
          headers: {
            'Accept': 'application/json'
          },
          credentials: 'include'
        })
        .then(response => {
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          return response.json();
        })
        .then(data => {
          if (!data || !data.datas) {
            throw new Error('无效的项目数据');
          }
          const projects = JSON.parse(data.datas);
          if (!projects || projects.length === 0) {
            throw new Error('未找到匹配的项目');
          }
          
          const project = projects[0];
          // 设置项目ID到隐藏输入框
          const hiddenInput = document.getElementById(fieldId);
          if (hiddenInput) {
            hiddenInput.value = project.id;
            hiddenInput.dispatchEvent(new Event('change', { bubbles: true }));
          }
  
          // 设置显示名称（只显示选中的项目名称）
          const projectInput = document.querySelector('.field8440_swapDiv .ant-select-search__field');
          if (projectInput) {
            projectInput.value = project.name;
            projectInput.dispatchEvent(new Event('change', { bubbles: true }));
          }
  
          // 调用确认接口
          const confirmParams = new URLSearchParams({
            requestid: '-1',
            workflowid: '103',
            nodeid: '619',
            formid: '-93',
            isbill: '1',
            triSource: '1',
            showAI: '0',
            triFieldid_256: '8440',
            rowIndexStr_256: '-1',
            triTableMark_256: 'main',
            field8440: project.id,
            linkageid: '256',
            wfTestStr: '',
            f_weaver_belongto_userid: '278',
            f_weaver_belongto_usertype: '0'
          });
  
          return fetch('https://oa.shenglong-info.com/api/workflow/linkage/reqDataInputResult', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: confirmParams
          });
        })
        .then(data => {
            if (data && data.assignInfo_256 && data.assignInfo_256.changeValue) {
                // 设置项目编号
                const projectNoInput = document.getElementById('field8441');
                const projectNoSpan = document.getElementById('field8441span');
                if (projectNoInput && projectNoSpan) {
                    const projectNo = data.assignInfo_256.changeValue.field8441.value;
                    projectNoInput.value = projectNo;
                    projectNoSpan.textContent = projectNo;
                    projectNoInput.dispatchEvent(new Event('change', { bubbles: true }));
                }
            }
        })
        .catch(error => {
            console.error('项目名称填充错误:', error);
            alert('获取项目信息失败，请确保已登录系统并重试');
        });
      } else {
        // 处理其他字段...
      }
    } catch (e) {
      console.error(`填充字段 ${fieldId} 时出错:`, e);
    }
  }
}

// 生成元素的唯一选择器
function generateSelector(element) {
  if (element.id) {
    return '#' + element.id;
  }
  if (element.name) {
    return `[name="${element.name}"]`;
  }
  let path = [];
  while (element.parentNode) {
    let selector = element.tagName.toLowerCase();
    let siblings = element.parentNode.children;
    if (siblings.length > 1) {
      let index = Array.prototype.indexOf.call(siblings, element) + 1;
      selector += `:nth-child(${index})`;
    }
    path.unshift(selector);
    element = element.parentNode;
    if (element.id) {
      path.unshift('#' + element.id);
      break;
    }
  }
  return path.join(' > ');
}
// 创建浮动图标
const icon = document.createElement('div');
icon.className = 'form-filler-icon';
icon.innerHTML = 'F';
icon.title = '表单填充器';
icon.style.cssText = `
    position: fixed;
    right: 20px;
    top: 20px;
    width: 40px;
    height: 40px;
    background: #4CAF50;
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-weight: bold;
    z-index: 10000;
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
`;

// 创建弹出框
const popup = document.createElement('div');
popup.style.cssText = `
    position: fixed;
    right: 70px;
    top: 20px;
    width: 300px;
    background: white;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    z-index: 9999;
    display: none;
`;

// 添加表单内容
popup.innerHTML = `
    <div style="margin-bottom: 10px;">
        <label>工作日期</label>
        <input type="text" id="field8413" style="width: 100%; margin-top: 5px; padding: 5px;">
    </div>
    <div style="margin-bottom: 10px;">
        <label>项目名称</label>
        <input type="text" id="field8440" style="width: 100%; margin-top: 5px; padding: 5px;">
    </div>
    <div style="margin-bottom: 10px;">
        <label>工作地点</label>
        <input type="text" id="field8435" style="width: 100%; margin-top: 5px; padding: 5px;">
    </div>
    <div style="margin-bottom: 10px;">
        <label>本日工作总结</label>
        <textarea id="field8411" style="width: 100%; margin-top: 5px; padding: 5px; height: 60px;"></textarea>
    </div>
    <div style="margin-bottom: 10px;">
        <label>明日工作计划</label>
        <textarea id="field8412" style="width: 100%; margin-top: 5px; padding: 5px; height: 60px;"></textarea>
    </div>
    <div style="margin-bottom: 10px;">
        <label>存在的问题和解决方案</label>
        <textarea id="field8410" style="width: 100%; margin-top: 5px; padding: 5px; height: 60px;"></textarea>
    </div>
    <button id="fillFormBtn" style="width: 100%; padding: 8px; background: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer;">
        填充表单
    </button>
`;

document.body.appendChild(popup);
document.body.appendChild(icon);

// 点击图标显示/隐藏弹框
icon.addEventListener('click', function() {
    popup.style.display = popup.style.display === 'none' ? 'block' : 'none';
});

// 点击其他地方关闭弹框
document.addEventListener('click', function(e) {
    if (!popup.contains(e.target) && !icon.contains(e.target)) {
        popup.style.display = 'none';
    }
});

// 填充表单按钮点击事件
document.getElementById('fillFormBtn').addEventListener('click', function() {
    const values = {};
    ['field8413', 'field8440', 'field8435', 'field8411', 'field8412', 'field8410'].forEach(fieldId => {
        values[fieldId] = document.getElementById(fieldId).value;
    });
    
    // 调用填充函数
    fillFormFields(values);
    popup.style.display = 'none';
});
